<?php
/**
 * Created by PhpStorm.
 * User: yyq
 * Date: 2018/9/26
 * Time: 11:20
 */

namespace Common\Model;


class CartModel extends CommonModel
{

    /**
     * @param $pro_id
     * @param $limit
     * @return int
     */
    public function getCode($pro_id, $limit) {

        $order_product_model = new OrderProductModel();
        $total_number = [];
        for($i = 1; $i < $limit+1; $i++) {
            $total_number[] = $i;
        }
        //查出购物车中已占用号
        $cart = $this->where(['pro_id' => $pro_id])->select();
        $cart_number = array_column($cart, 'number');

        //查出订单已占用的号
        $order = $order_product_model->where(['pro_id' => $pro_id, 'status' => ['in', [OrderModel::STATUS_WAIT, OrderModel::STATUS_WAIT_FOR_PAY, OrderModel::STATUS_COMPLETE, OrderModel::STATUS_SEND,OrderModel::STATUS_PAY_SUCCESS, OrderModel::STATUS_RETURN]]])->select();
        $order_number = array_column($order, 'number');

        $total_number = array_diff($total_number, $cart_number, $order_number);

        $number = $total_number[array_rand($total_number)];

        return $number;
    }

    /**
     * 2天自动取消选号
     */
    public function dealCart() {
        $where['number_time'] = ['lt', date('Y-m-d H:i:s', time()-3600*24*2)];
        $this->where($where)->save(['number' => '', 'number_time' => NULL]);
    }
}